﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace ManagementProject
{
    public partial class frmShippers : Form
    {
        SqlConnection con;
        SqlDataAdapter da;
        DataSet ds;
        SqlCommandBuilder cb;
        DataTable dt;
        DataView dv;
        bool change = false;
        public frmShippers()
        {
            InitializeComponent();
            InitializeADOObject();
        }

        void InitializeADOObject()
        {
            try
            {
                con = new SqlConnection();
                con.ConnectionString = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "getShippers";
                da = new SqlDataAdapter(cmd);
                cb = new SqlCommandBuilder(da);
                ds = new DataSet();
                da.FillSchema(ds, SchemaType.Mapped);
                da.Fill(ds, "Sales.Shippers");
                cboSearch.SelectedIndex = 0;
            }
            catch (Exception)
            {
                MessageBox.Show("Fail connection!");
            }
        }

        #region Validate, Load, Add, Update, Delete, Search
        bool validateInput()
        {
            bool error = false;
            string s = "";
            s = txtCompanyName.Text;
            if (s.Trim().Length == 0)
            {
                errorProvider1.SetError(txtCompanyName, "Please enter Companyname!");
                error = true;
            }
            if (s.Length > 40)
            {
                errorProvider1.SetError(txtCompanyName, "Companyname not greater than 40 character");
                error = true;
            }
            if (mtxtPhone.MaskCompleted == false)
            {
                errorProvider1.SetError(mtxtPhone, "please enter required digit!");
                error = true;
            }
            if (error == true)
            {
                return false;
            }
            else
                errorProvider1.Clear();
            return true;
        }

        void LoadShippers()
        {

            try
            {
                dt = ds.Tables["Sales.Shippers"];
                dv = new DataView(dt);
                gvShippers.DataSource = dt;
            }
            catch (Exception e)
            {
                MessageBox.Show("ERORR!" + e.Message);
                gvShippers = null;
            }


        }

        void addNewShipper()
        {
            try
            {
                dt = ds.Tables["Sales.Shippers"];
                DataRow r = dt.NewRow();
                r["companyname"] = txtCompanyName.Text;
                r["phone"] = mtxtPhone.Text;         
                dt.Rows.Add(r);
                da.Update(dt);
            }
            catch (Exception e)
            {
                MessageBox.Show("ERORR!" + e.Message);

            }
        }

        void updateShipper()
        {
            if (gvShippers.SelectedRows.Count > 0)
            {
                try
                {
                    dt = ds.Tables["Sales.Shippers"];
                    DataGridViewRow rv = gvShippers.SelectedRows[0];
                    DataRow[] r = dt.Select(string.Format("shipperid = '{0}'", rv.Cells["shipperid"].Value.ToString()));
                    r[0]["companyname"] = txtCompanyName.Text;
                    r[0]["phone"] = mtxtPhone.Text;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }             
            }
        }

        void deleteShipper()
        {
            if (gvShippers.SelectedRows.Count > 0)
            {
                DataGridViewRow rv = gvShippers.SelectedRows[0];
                dv = new DataView(dt);
                dv.RowFilter = string.Format("shipperid = '{0}'", rv.Cells["shipperid"].Value.ToString());
                dv.Delete(0);
            }
        }

        void defaultShipper()
        {
            btnUpdate.Enabled = false;
            btnDelete.Enabled = false;
            btnSavetoDatabase.Enabled = true;
            btnAdd.Enabled = true;
            txtShipperid.Clear();
            txtCompanyName.Clear();
            mtxtPhone.Clear();
        }

        void SearchbyCompanyName()
        {

            dv = new DataView(dt);
            dv.RowFilter = string.Format("companyname like '%{0}%'", txtSearch.Text);
            gvShippers.DataSource = dv;
        }

        void SearchbyID()
        {

            dv = new DataView(dt);
            dv.RowFilter = string.Format("shipperid = '{0}'", txtSearch.Text);
            gvShippers.DataSource = dv;
        }
        #endregion

        private void btnNew_Click(object sender, EventArgs e)
        {
            defaultShipper();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (!validateInput())
                return;
            else
            {
                addNewShipper();
                InitializeADOObject();
                LoadShippers();
                defaultShipper();
                MessageBox.Show("Add compelete ");
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DialogResult rs = MessageBox.Show("Are you sure to delete!", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (rs == DialogResult.Yes)
            {
                try
                {
                    deleteShipper();
                    change = true;
                    da.Update(dt);
                    defaultShipper();
                    btnSavetoDatabase.Enabled = true;
                    MessageBox.Show("Delete compelete ");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("This item cannot delete!!" + ex.Message);
                }
            }
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!validateInput())
                return;
            else
            {
                updateShipper();
                defaultShipper();
                change = true;
                btnSavetoDatabase.Enabled = true;
                MessageBox.Show("Update compelete ");
            }
        }

        private void btnSavetoDatabase_Click(object sender, EventArgs e)
        {
            DialogResult rs = MessageBox.Show("Are you sure to Save!", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (rs == DialogResult.Yes)
            {
                dt = ds.Tables["Sales.Shippers"];
                try
                {
                    da.Update(dt);
                    change = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void FrmShippers_Load(object sender, EventArgs e)
        {
            LoadShippers();
        }

        private void gvShippers_SelectionChanged(object sender, EventArgs e)
        {
            if (gvShippers.SelectedRows.Count > 0)
            {
                btnUpdate.Enabled = true;
                btnDelete.Enabled = true;
                btnAdd.Enabled = false;
                DataGridViewRow r = gvShippers.SelectedRows[0];
                txtShipperid.Text = r.Cells["shipperid"].Value.ToString();
                txtCompanyName.Text = r.Cells["companyname"].Value.ToString();
                mtxtPhone.Text = r.Cells["phone"].Value.ToString();
            }
        }   

        private void btnShowAll_Click(object sender, EventArgs e)
        {
            gvShippers.DataSource = dt;
            txtSearch.Text = "";
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            string search = cboSearch.Text;
            if (search == "Company Name")
            {
                SearchbyCompanyName();
            }
            else
                if (search == "ID")
                {
                    SearchbyID();
                }
        }

        private void FrmShippers_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (change)
            {
                DialogResult rs = MessageBox.Show("Save Change to Database?", "Confirm", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (rs == DialogResult.Yes)
                {
                    dt = ds.Tables["Sales.Shippers"];
                    try
                    {
                        da.Update(dt);
                    }
                    catch (Exception ex)
                    {

                        MessageBox.Show(ex.Message);
                    }
                }
                else
                    if (rs == DialogResult.Cancel)
                        e.Cancel = true;
            }
        }
    }

}
